package com.peak.distribution.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.peak.distribution.entity.admin.DisRole;
import com.peak.distribution.entity.admin.DisUser;
import com.peak.distribution.entity.agent.DisAgent;
import com.peak.distribution.enums.RoleType;
import com.peak.distribution.exception.DistributionError;
import com.peak.distribution.manager.admin.DisUserManager;
import com.peak.distribution.manager.agent.DisAgentManager;
import com.peak.spring.boot.core.mapper.BeanMapper;

/**
 * 登录的时候根据用户名取用户信息的功能
 * 
 * @author Haley Gao
 *
 */
@Service
@Transactional(readOnly = true)
public class SessionUserDetailsService implements UserDetailsService {

	@Autowired
	private DisUserManager userManager;

	@Autowired
	private DisAgentManager agentManager;

	/**
	 * 根据登录名，获取用户的信息
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		DisUser user = userManager.getByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException(DistributionError.USER_LOGIN_NOT_FOUNT.getMessage());
		}
		DisRole role = user.getRole();
		if (role == null) {
			throw new UsernameNotFoundException(DistributionError.USER_LOGIN_NOT_FOUNT_ROLE.getMessage());
		}
		// 存入session中的user对象数据
		SessionUser sessionUser = BeanMapper.copy(user, SessionUser.class);
		
		if (RoleType.AGENT.equals(role.getType())) {
			// 把代理的信息取出来，以后有管理员还需要把管理员的信息取出来
			DisAgent agent = agentManager.getByUserId(user.getId());
			if (agent == null) {
				throw new UsernameNotFoundException(DistributionError.USER_LOGIN_NOT_FOUNT.getMessage());
			}
			// 存入session中的agent对象数据
			sessionUser.setHeadUrl(agent.getHeadUrl());
			sessionUser.setName(agent.getName());
			sessionUser.setMobileNo(agent.getMobileNo());
			sessionUser.setAgentId(agent.getId());
		}
		// 给角色名和成功跳转的链接
		sessionUser.setRoleName(role.getName());
		sessionUser.setDefaultSuccessUrl(role.getSuccessUrl());
		return sessionUser;
	}

}
